<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>动态表头测试</title>
    <script th:src="@{/webjars/jquery/3.3.1/jquery.js}" type="text/javascript"></script>
    <style>
        #tableContainer {
            width: 100%;
            overflow: auto;
        }

        /*<!--表格样式-->*/
        #kpiTable {
            /*width: 100%;*/
            background-color: #f2f2f2;
        }

        /*单元格样式*/
        #kpiTable td {
            width: 200px;
            height: 30px;
        }

        /*表头样式*/
        /*#kpiTable th {*/
        /*width: 200px;*/
        /*height: 30px;*/
        /*}*/

        /*二级列表头*/
        .rowTh, .lv2ColTh {
            font-family: "楷体", "DejaVu Sans Mono", sans-serif;
            font-size: 20px;
        }

        /*一级列表头*/
        .lv1ColTh {
            font-family: "Adobe 黑体 Std R", "DejaVu Sans Mono", sans-serif;
            font-size: 22px;
        }

        #colHeader th {
            width: 200px;
        }

        /*表头颜色样式*/
        th {
            background-color: silver;
        }

        /*可编辑单元格文本框*/
        input.cell {
            width: 100%;
            height: 100%;
            font-size: 100%;
            border: 0;
        }

        .editable {
            background-color: #f3f4f4;
        }
    </style>
    <script>

        var editing = false;
        var ALL_AREAS = ['1', '2'];
        var ALL_COLS = ['COL0', 'COL1', 'COL2'];

        function test(param1, param2) {
            if(param2 === undefined){
                param2 = true;
            }
            if(param2){
                console.log("param2 True");
            }
        }
        
        function editTable() {
            console.log('点击编辑按钮');
            if (!editing) {
                var editableTdArr = $('.editable');
                $.each(editableTdArr, function (index, item) {
                    var inputCls = 'cell';
                    if ($(item).hasClass('computable')) {
                        inputCls += ' computable';
                    }
                    var text = $(item).html();
                    $(item).html('<input type="text" class="' + inputCls + '" value="' + text + '"/>');
                });
                editing = true;

                $('input.cell.computable').bind('input propertychange', function (event) {
                    var parentTd = $(this).parent('.editable');
                    calSum(parentTd.attr('area'), parentTd.attr('colCode'));
                });

            }

        }


        function calSum(areaStr, colCode) {

            var areas = areaStr.split(',');
            if (areas.length > 1) {
                var sumTdSelector = 'td[sum="' + areaStr + '"][colCode="' + colCode + '"]';
                var multiSumTd = $(sumTdSelector);
                if (multiSumTd && (multiSumTd.length === 1)) {
                    var sum = 0;
                    for (var i = 0; i < areas.length; i++) {
                        var singleSumTdSelector = 'td[sum="' + areas[i] + '"][colCode="' + colCode + '"]';
                        var singleSumTd = $(singleSumTdSelector);
                        if (singleSumTd && singleSumTd.length > 0) {
                            sum += toNumber(singleSumTd.html());
                        } else {
                            sum += calSingleAreaSum(areas[i], colCode);
                        }
                    }
                    multiSumTd.html(formatNum(sum, 4));
                }
            } else {
                calSingleAreaSum(areaStr, colCode);
                var multiSumTdSelector = 'td[sum*="' + areaStr + '"][sum!="' + areaStr + '"][colCode="' + colCode + '"]';
                var multiSumTds = $(multiSumTdSelector);
                for (var j = 0; j < multiSumTds.length; j++) {
                    var sumTd = $(multiSumTds[j]);
                    calSum(sumTd.attr('sum'), colCode);
                }
            }

        }

        //单个区域单元格求和
        function calSingleAreaSum(area, colCode) {
            var sumTdSelector = 'td[sum="' + area + '"][colCode="' + colCode + '"]';
            var sumTd = $(sumTdSelector);

            var tdsSelector = 'td[area="' + area + '"][colCode="' + colCode + '"]';
            var tdArr = $(tdsSelector);

            var sum = 0;
            if (editing) {
                $.each(tdArr, function (index, item) {
                    var td = $(item);
                    var value;
                    if (td.hasClass('editable')) {
                        var input = td.find('input');
                        value = input.val().trim();
                    } else {
                        value = td.html().trim();
                    }
                    sum += toNumber(value);
                });
            } else {
                $.each(tdArr, function (index, item) {
                    var td = $(item);
                    var tdHtml = td.html();
                    sum += toNumber(tdHtml);
                });
            }

            if (sumTd && sumTd.length > 0) {
                sumTd.html(formatNum(sum, 4));
            }
            return formatNum(sum, 4);
        }

        function save() {
            console.log("点击保存按钮");
            if (editing) {
                var tdInputArr = $('.cell');
                $.each(tdInputArr, function (index, item) {
                    var tdObj = $(item).parent('.editable');
                    tdObj.html($(item).val());
                });
                editing = false;
            }
        }

        function formatNum(f, digit) {
            var m = Math.pow(10, digit);
            return Math.round(f * m) / m;
        }

        function toNumber(str) {
            if (str && str.trim() !== '' && !isNaN(str)) {
                return parseFloat(str);
            } else {
                return 0;
            }
        }

        $(function () {

            initTable();

            for (var i = 0; i < ALL_AREAS.length; i++) {
                var area = ALL_AREAS[i];
                for (var j = 0; j < ALL_COLS.length; j++) {
                    var col = ALL_COLS[j];
                    calSum(area, col);
                }

            }


            // $.each(sumTds, function (index, item) {
            //     var sumTd = $(item);
            //     var sumArea = sumTd.attr('sum');
            //     var colCode = sumTd.attr('colCode');
            //     var sum = 0;
            //
            //     var selector = 'td[area="' + sumArea + '"][colCode="' + colCode + '"]';
            //     var tdArr = $(selector);
            //     $.each(tdArr, function (i, tdItem) {
            //         var td = $(tdItem);
            //         var tdHtml = td.html().trim();
            //         if (tdHtml !== '' && !isNaN(tdHtml)) {
            //             sum += parseFloat(tdHtml);
            //         }
            //     });
            //
            //     sumTd.html(formatNum(sum, 4));
            //
            // });
            // var tdArr = $("td.editableTd");

            // var inputObj = $('<input type="text" class="cell"/>');

            // $.each(tdArr, function (index, item) {
            //     $(item).html('<input type="text" class="cell"/>');
            // });

            // console.log(tdArr.length);
            // tdArr.forEach(function (val, index) {
            //     console.log(index)
            // });

            // tdArr.click(function(){
            //
            //     //找到当前鼠标点击的td
            //     var tdObj=$(this);
            //     //
            //     if(tdObj.children("input").length>0){
            //         //当前td中的input，不执行click处理
            //         return false;
            //     }
            //     var text=tdObj.html();
            //     //清空td的内容
            //     tdObj.html("");
            //
            //     //创建一个文本框
            //     //去掉文本框的边框
            //     //文本框的文字大小16px
            //     //文本框的宽度与td相同
            //     //设置文本框的背景色
            //     //将td中的内容放到文本框中
            //     //将文本框插入到td中
            //     var inputObj=$("<input type='text' />").css("border-width","0")
            //         .css("font-size","16px")
            //         .width(tdObj.width())
            //         .css("background-color",tdObj.css("background-color"))
            //         .css("font",tdObj.css("font"))
            //         .val(text)
            //         .appendTo(tdObj);
            //     //文本框插入后被选中
            //     //inputObj.get(0).select();
            //     inputObj.trigger("focus").trigger("select");
            //     inputObj.click(function(){
            //         return false;
            //     });
            //     //处理文本框的回车和Esc操作
            //     inputObj.keyup(function(event){
            //         //获取键值
            //         var keycode=event.which;
            //         //回车
            //         if(keycode==13){
            //             //获取当前文本框的内容
            //             var inputText=$(this).val();
            //             //将td的内容修改为文本框的内容
            //             tdObj.html(inputText);
            //         }
            //
            //         //esc情况,
            //         //将td的内容还原成text
            //         if(keycode==27){
            //             tdObj.html(text);
            //         }
            //
            //     });
            //
            // });

            // for (var i = 0; i < tdArr.length; i ++){
            //     inputObj.appendTo(tdArr[i]);
            // }
            //     .forEach(function(index, item){
            //     console.log(index);
            // });
        });

        var prosCodeArr = ['KH_001', 'KH_002', 'GM_001', 'GM_002', 'XS_001', 'XS_002', 'XS_003', 'SR_001', 'SR_002', 'SR_003', 'SR_004', 'SR_005', 'SR_006', 'SR_007', 'SR_008'];
        var CODE_LIST = 'LIST_COUNT';
        var CODE_WEEK = ['WEEK_COUNT_1', 'WEEK_COUNT_2', 'WEEK_COUNT_3', 'WEEK_COUNT_4'];
        var pros = {
            'PRO_KH': {
                name: '客户类',
                prods: [{
                    name: '私行',
                    code: 'KH_001',
                    taskValue: 1232
                }, {
                    name: '贵宾',
                    code: 'KH_002',
                    taskValue: 1232
                }]
            },
            'PRO_GM': {
                name: '规模类',
                prods: [{
                    name: 'AUM',
                    code: 'GM_001',
                    taskValue: 1232
                }, {
                    name: '结构性存款净增量',
                    code: 'GM_002',
                    taskValue: 1232
                }]
            },
            'PRO_XS': {
                name: '销售类',
                prods: [{
                    name: '非货基向量',
                    code: 'XS_001',
                    taskValue: 1232
                }, {
                    name: '期缴销量',
                    code: 'XS_002',
                    taskValue: 1232
                }, {
                    name: '趸缴销量',
                    code: 'XS_003',
                    taskValue: 1232
                }]
            },
            'PRO_SR': {
                name: '收入类',
                prods: [{
                    name: '收入类指标1',
                    code: 'SR_001',
                    taskValue: 1232
                }, {
                    name: '收入类指标2',
                    code: 'SR_002',
                    taskValue: 1232
                }, {
                    name: '收入类指标3',
                    code: 'SR_003',
                    taskValue: 1232
                }, {
                    name: '收入类指标4',
                    code: 'SR_004',
                    taskValue: 1232
                }, {
                    name: '收入类指标5',
                    code: 'SR_005',
                    taskValue: 1232
                }, {
                    name: '收入类指标6',
                    code: 'SR_006',
                    taskValue: 1232
                }, {
                    name: '收入类指标7',
                    code: 'SR_007',
                    taskValue: 1232
                }, {
                    name: '收入类指标8',
                    code: 'SR_008',
                    taskValue: 1232
                }]
            }
        };

        var HOActivity = {
            'MY': {
                name: '蜜月',
                details: [{
                    name: '新客户基础套餐配置',
                    code: 'MY_1'
                }, {
                    name: '新开客户首月临界',
                    code: 'MY_2'
                }, {
                    name: '新开客户第二个月临界',
                    code: 'MY_3'
                }, {
                    name: '新开客户第三个月临界',
                    code: 'MY_4'
                }, {
                    name: '开户三个月内新贵宾客户',
                    code: 'MY_5'
                }]
            },
            'TS': {
                name: '提升',
                details: [{
                    name: '潜力贵宾客户提升',
                    code: 'TS_1'
                }, {
                    name: '贵宾客户提升',
                    code: 'TS_2'
                }, {
                    name: '开户三个月以上新晋升为贵宾客户',
                    code: 'TS_3'
                }]
            },
            'WD': {
                name: '稳定',
                details: [{
                    name: '客户资产配置健诊名单',
                    code: 'WD_1'
                }]
            },
            'FJ': {
                name: '防降',
                details: [{
                    name: '防降名单',
                    code: 'FJ_1'
                }]
            },
            'YH': {
                name: '赢回',
                details: [{
                    name: '贵宾客户新降级(30天)',
                    code: 'YH_1'
                }, {
                    name: '贵宾客户新降级(60天)',
                    code: 'YH_2'
                }, {
                    name: '贵宾客户新降级(90天)',
                    code: 'YH_3'
                }]
            }
        };

        var tableHtml = '';

        function initTable() {
            // initProsHeader();
            // initHOTr();
            // console.log(tableHtml);
            // $('#kpiTable').html(tableHtml);
        }

        function initProsHeader() {
            var kindTrHtml = '<tr><th rowspan="2">项目</th>';
            var prodsTrHtml = '<tr>';
            var taskValueTrHtml = '<tr><th>目标数</th>';
            var predictionTrHtml = '<tr id="colHeader"><th>总行</th><th colspan="3">事件触发</th><th>名单数</th>';
            for (var key in pros) {
                var proKind = pros[key];
                var prods = proKind['prods'];
                kindTrHtml += '<th colspan="' + prods.length + '">' + proKind['name'] + '</th>';
                for (var i = 0; i < prods.length; i++) {
                    var pro = prods[i];
                    prodsTrHtml += '<th>' + pro['name'] + '</th>';
                    taskValueTrHtml += '<td>' + pro['taskValue'] + '</td>';
                    predictionTrHtml += '<th>' + (pro['name'] + '预估值') + '</th>';
                }
            }
            kindTrHtml += '<th colspan="8"></th></tr>';
            prodsTrHtml += '<th colspan="8"></th></tr>';
            taskValueTrHtml += '<th colspan="8"></th></tr>';
            predictionTrHtml +=
                '<th>第一周执行名单数</th>'
                + '<th>第二周执行名单数</th>'
                + '<th>第三周执行名单数</th>'
                + '<th>第四周执行名单数</th>'
                + '</tr>';

            tableHtml += kindTrHtml + prodsTrHtml + taskValueTrHtml + predictionTrHtml;
        }

        function initHOTr() {
            var HOActivityHtml = '';
            for (var key in HOActivity) {
                var activity = HOActivity[key];
                var details = activity['details'];
                var rowHtml = '<th rowspan="' + details.length + '">' + activity['name'] + '</th>';
                for (var i = 0; i < details.length; i++) {
                    var detail = details[i];
                    rowHtml += '<th colspan="3">' + detail['name'] + '</th>';
                    rowHtml += generateEditableTrHtml(detail['code'], '1');
                    HOActivityHtml += '<tr>' + rowHtml + '</tr>';
                    rowHtml = '';
                }

            }
            var sumTrHtml = '<tr><th></th><th colspan="3">总行名单统计</th>' + generateSumTrHtml('SUM_1', '1') + '</tr>';
            HOActivityHtml += sumTrHtml;
            tableHtml += HOActivityHtml;
        }


        function generateEditableTrHtml(rowCode, area) {
            var result = '';
            var listClass = 'computable';
            if (area !== '1' && area !== '2') {
                listClass += ' editable';
            }
            //名单数
            result += '<td area="' + area + '" colcode="' + CODE_LIST + '" rowCode="' + rowCode + '" class="' + listClass + '"></td>';
            //预期值
            for (var i = 0; i < prosCodeArr.length; i++) {
                var proCode = prosCodeArr[i];
                result += '<td area="' + area + '" colcode="' + proCode + '" rowCode="' + rowCode + '" class="computable editable"></td>';
            }
            //四周
            for (var j = 0; j < CODE_WEEK.length; j++) {
                var weekCode = CODE_WEEK[i];
                result += '<td area="' + area + '" colcode="' + weekCode + '" rowCode="' + rowCode + '" class="computable editable"></td>';
            }
            return result;

        }

        function generateSumTrHtml(rowCode, area) {
            var result = '';
            //名单数
            result += '<td sum="' + area + '" colcode="' + CODE_LIST + '" rowCode="' + rowCode + '"></td>';
            //预期值
            for (var i = 0; i < prosCodeArr.length; i++) {
                var proCode = prosCodeArr[i];
                result += '<td sum="' + area + '" colcode="' + proCode + '" rowCode="' + rowCode + '"></td>';
            }
            //四周
            for (var j = 0; j < CODE_WEEK.length; j++) {
                var weekCode = CODE_WEEK[i];
                result += '<td sum="' + area + '" colcode="' + weekCode + '" rowCode="' + rowCode + '"></td>';
            }
            return result;
        }

    </script>
</head>
<body>
<input type="button" value="编辑" onclick="editTable()">
<input type="button" value="保存" onclick="save()">
<div id="tableContainer">
    <table id="kpiTable" cellspacing="0" border="1">

        <tr>
            <th>总行</th>
            <th>事件触发</th>
            <th>名单数</th>
            <th>预估达成客户数</th>
            <th>预估达成AUM</th>
        </tr>

        <tr>
            <th rowspan="5">蜜月</th>
            <th>新客户基础套餐配置（厅堂活动量）</th>
            <td area="1" colCode="COL0">12</td>
            <td area="1" colCode="COL1" class="editable computable">鲁俊伟</td>
            <td area="1" colCode="COL2" class="editable computable">23</td>
        </tr>

        <tr>
            <th>新开客户首月临界</th>
            <td area="1" colCode="COL0">15</td>
            <td area="1" colCode="COL1" class="editable computable">33</td>
            <td area="1" colCode="COL2" class="editable computable">55</td>
        </tr>

        <tr>
            <th>新开客户第二个月临界</th>
            <td area="1" colCode="COL0">18</td>
            <td area="1" colCode="COL1" class="editable computable">44</td>
            <td area="1" colCode="COL2" class="editable computable">45</td>
        </tr>

        <tr>
            <th>新开客户第三个月临界（是否已在潜客提升阶段？）</th>
            <td area="1" colCode="COL0">23</td>
            <td area="1" colCode="COL1" class="editable computable">66</td>
            <td area="1" colCode="COL2" class="editable computable">67</td>
        </tr>

        <tr>
            <th>开户三个月内新贵宾客户</th>
            <td area="1" colCode="COL0">56</td>
            <td area="1" colCode="COL1" class="editable computable">77</td>
            <td area="1" colCode="COL2" class="editable computable">78</td>
        </tr>

        <tr>
            <th></th>
            <th>总行名单合计</th>
            <td></td>
            <td></td>
            <td></td>
            <!--<td sum="1" colCode="COL0"></td>-->
            <!--<td sum="1" colCode="COL1"></td>-->
            <!--<td sum="1" colCode="COL2"></td>-->
        </tr>
        <tr>
            <th rowspan="6">沙龙</th>
            <th class="editable"></th>
            <td area="2" colCode="COL0" class="editable computable"></td>
            <td area="2" colCode="COL1" class="editable computable"></td>
            <td area="2" colCode="COL2" class="editable computable"></td>
        </tr>
        <tr>
            <th class="editable"></th>
            <td area="2" colCode="COL0" class="editable computable"></td>
            <td area="2" colCode="COL1" class="editable computable"></td>
            <td area="2" colCode="COL2" class="editable computable"></td>
        </tr>
        <tr>
            <th class="editable"></th>
            <td area="2" colCode="COL0" class="editable computable"></td>
            <td area="2" colCode="COL1" class="editable computable"></td>
            <td area="2" colCode="COL2" class="editable computable"></td>
        </tr>
        <tr>
            <th class="editable"></th>
            <td area="2" colCode="COL0" class="editable computable"></td>
            <td area="2" colCode="COL1" class="editable computable"></td>
            <td area="2" colCode="COL2" class="editable computable"></td>
        </tr>
        <tr>
            <th class="editable"></th>
            <td area="2" colCode="COL0" class="editable computable"></td>
            <td area="2" colCode="COL1" class="editable computable"></td>
            <td area="2" colCode="COL2" class="editable computable"></td>
        </tr>
        <tr>
            <th>沙龙合计</th>
            <td sum="2" colCode="COL0"></td>
            <td sum="2" colCode="COL1"></td>
            <td sum="2" colCode="COL2"></td>
        </tr>
        <tr>
            <th colspan="2">总合计</th>
            <td sum="1,2" colCode="COL0"></td>
            <td sum="1,2" colCode="COL1"></td>
            <td sum="1,2" colCode="COL2"></td>
        </tr>

    </table>
</div>


</body>
</html>